//<!-- 月票凭证配置 -->
import {
  deepCopyObj,
  deepCopyObjArray,
  getTreeChildNodes,
  adjustProvinceNameOfParkingLot
} from '../../../assets/js/help.js'

export default {
  data() {
    return {
      parkNameListRow: {
        searchParams: {},
        pageNumber: 1,
        total: 0,
        theadsInfo: [{
            index: 0,
            isShow: false,
            prop: 'reno',
            text: '序号',
            width: 68
          },
          {
            index: 1,
            isShow: false,
            prop: 'm',
            text: '停车场',
            minWidth: 110
          }
        ],
        tbodysInfo: []
      },
      parkNameRow: {},
      bigImgPath: '',
      agreenment: {
        title: null,
        content: null,
        id: null,
        parkId: null,
        parkName: ''
      },
      certifi_rule_modal_title: '',
      certifiRuleModel: {
        parkId: null,
        parkName: '',
        certifiStatus: 1,
        certifiType: null,
        certifiSample: null,
        certifiSampleName: null,
        certifiSampleUrl: null,
        inCertifiDesc: null,
        outCertifiSample: null,
        outCertifiSampleName: null,
        outCertifiSampleUrl: null,
        outCertifiDesc: null,
        agreementId: null,
        agreementTitle: null,
        agreementContent: null,
        monthTicketNames: null,
        monthTicketConfigIds: null,
      },
      list: [],
      agreementEdit: null,
      certifiRuleEdit: null,
      certifiRuleRules: {
        certifiName: [{
            required: true,
            message: '请输入凭证名称',
            trigger: 'change'
          },
          {
            min: 1,
            max: 50,
            message: '长度在 1 到 50 个字符',
            trigger: 'change'
          }
        ],
        certifiType: [{
          required: true,
          message: '请选择凭证状态'
        }],
        certifiStatus: [{
          required: true,
          message: '请选择凭证种类'
        }],
        parkId: [{
          required: true,
          message: '请选择停车场协议'
        }],
        certifiDesc: [{
          min: 0,
          max: 500,
          message: '长度在 0 到 500 个字符',
          trigger: 'change'
        }],
        outCertifiDesc: [{
            required: true,
            message: '请输入对外凭证说明'
          },
          {
            min: 2,
            max: 500,
            message: '长度在 2 到 500 个字符',
            trigger: 'change'
          }
        ],
        title: [{
            required: true,
            message: '请输入协议名称'
          },
          {
            min: 2,
            max: 50,
            message: '长度在 2 到 50 个字符',
            trigger: 'change'
          }
        ],
        content: [{
            required: true,
            message: '请输入协议内容'
          },
          {
            min: 2,
            max: 1000,
            message: '长度在 2 到 1000 个字符',
            trigger: 'change'
          }
        ],
        certifiSampleUrl: [{
          required: true,
          message: '请上传对内凭证样例',
          trigger: 'change'
        }],
        outCertifiSampleUrl: [{
          required: true,
          message: '请上传对外凭证样例'
        }]
      },
      monthTicketConfigIdArr: [], //月票列表-已选的月票
      monthTicketList: [], //月票列表
      keyWord: '', //搜索月票-关键字
      parkingLotList: [], //停车场列表
      selectedMonthTicket: [], //新增or编辑已选择的月票
      selectedMonthTicketStr: '', //新增or编辑已选择的月票
      isShowMonthTicketVisiable: false, //是否查看适用月票
    }
  },
  created() {
    this.toBase(this);
  },
  methods: {
    // 获取所有停车场
    fetchParkingLotList(){
      let self = this;
      return API.fetchGet('/month_ticket/certifi_rule/findAllParks.do',{}).then(res => {
        let data = res.data;
        if (data) {
          self.list = data.map(item => {
            let obj = {
              value: item.id,
              label: item.name,
              key: item.id,
              area: '',
              topArea: ''
            }
            if(item.area){
              let arr = item.area.split('-')
              obj.area = item.area.replace(/-/g,' > ')
              obj.topArea = adjustProvinceNameOfParkingLot(arr[0])
            }
            return obj;
          });
        }
      }, err => {}); 
    },
    // 搜索月票
    searchMonthTicketKeyWord(){
      let self = this
      let keyWord = self.keyWord
      if(Array.isArray(self.monthTicketList) && self.monthTicketList.length){
        self.monthTicketList.forEach(elem=>{
          if(elem.name.indexOf(keyWord)>-1 || elem.parkNameStr.indexOf(keyWord)>-1){
            elem.isHidden = false
          }else{
            elem.isHidden = true
          }
        })
        self.monthTicketList.push({})
        self.monthTicketList.pop()
      }
    },
    //图片转bas64
    showBigImgModal(name, path) {
      this.bigImgPath = path;
      this.toOpenImgModal(name, path);
    },
    toBase(vm) {
      $(document).on('change', "#certifiSampleUrl", function () {
        var file = this.files[0];
        var reader = new FileReader();
        if (!/image\/\w+/.test(file.type)) {
          // icon: 0:普通提示 1：正确的提示 2： 错误提示
          // time: 不填默认1000ms
          vm.showToast('请确保文件为图像类型', 0, 2000);
          vm.certifiRuleModel.certifiSample = null;
          vm.certifiRuleModel.certifiSampleUrl = null;
          return false;
        }
        if (file && file.size > 2097152) {
          vm.showToast('请选择容量少于2M的图片', 0, 2000);
          vm.certifiRuleModel.certifiSample = null;
          vm.certifiRuleModel.certifiSampleUrl = null;
          return false;
        }
        vm.certifiRuleModel.certifiSampleName = file.name;
        reader.readAsDataURL(file);
        reader.onload = function (e) {
          var res = e.target.result.replace("data:image/png;base64,", "");
          res = res.replace("data:image/jpg;base64,", "");
          vm.certifiRuleModel.certifiSampleUrl = res;
          vm.$refs['certifi_rule_modal_form'].validateField('certifiSampleUrl')
          res = res.replace("data:image/jpeg;base64,", "");
          vm.certifiRuleModel.certifiSample = res;
        };
      });

      $(document).on('change', "#outCertifiSampleUrl", function () {
        var file = this.files[0];
        var reader = new FileReader();
        if (!/image\/\w+/.test(file.type)) {
          // icon: 0:普通提示 1：正确的提示 2： 错误提示
          // time: 不填默认1000ms
          vm.showToast('请确保文件为图像类型', 2, 2000)
          vm.certifiRuleModel.outCertifiSample = null;
          vm.certifiRuleModel.outCertifiSampleUrl = null;
          return false;
        }
        if (file && file.size > 2097152) {
          vm.showToast('请选择容量少于2M的图片', 2, 2000);
          vm.certifiRuleModel.outCertifiSample = null;
          vm.certifiRuleModel.outCertifiSampleUrl = null;
          return false;
        }
        vm.certifiRuleModel.outCertifiSampleName = file.name;
        reader.readAsDataURL(file);
        reader.onload = function (e) {
          var res = e.target.result.replace("data:image/png;base64,", "");
          res = res.replace("data:image/jpg;base64,", "");
          res = res.replace("data:image/jpeg;base64,", "");
          vm.certifiRuleModel.outCertifiSample = res;
          vm.certifiRuleModel.outCertifiSampleUrl = "res";
        };
      });
    },
    getList() {
      let params = $.extend({}, this.searchParams, this.otherParams);
      this.getCertifiRuleList(params);
    },
    getCertifiRuleList(aparams) { //查询列表
      let self = this,
        params = {
          page: this.pageNumber,
          rp: this.pageSize
        };
      params = $.extend({}, params, aparams);

      API.monthTicket.GetCertifiRuleListData(params)
        .then(res => {
          let data = res.data,
            list = data.rows;
          self.tbodysInfo = list;
          self.total = data.total;
        }, err => {})
    },
    resetModelData(certifiRuleEdit) {
      let self = this;
      self.certifiRuleEdit = certifiRuleEdit; //true or false
      self.certifiRuleModel = {
        parkName: '',
        parkId: null,
        certifiStatus: 1,
        certifiType: null,
        certifiSample: null,
        certifiSampleName: null,
        certifiSampleUrl: null,
        inCertifiDesc: null,
        outCertifiSample: null,
        outCertifiSampleName: null,
        outCertifiSampleUrl: null,
        outCertifiDesc: null,
        agreementId: null,
        agreementTitle: null,
        agreementContent: null,
        monthTicketNames: null,
        monthTicketConfigIds: null,
      }
      self.selectedMonthTicket = []
      self.selectedMonthTicketStr = ''
    },
    async addCertifiRule(modalName) {
      let self = this;
      self.resetModelData(true);
      self.certifi_rule_modal_title = '新增';
      await self.initParkTree()
      self.toOpenModal(modalName);
    },
    async editCertifiRule(modalName, row, certifiRuleEdit) {
      let self = this;
      self.resetModelData(certifiRuleEdit);
      if (certifiRuleEdit) {
        self.certifi_rule_modal_title = '修改';
        await self.initParkTree()
      } else {
        self.certifi_rule_modal_title = '查看';
      }
      self.certifiRuleModel = deepCopyObj(row);
      self.certifiRuleModel.parkId += ''
      self.certifiRuleModel.certifiStatus = row.certifiStatus;
      self.certifiRuleModel.certifiType = row.certifiType;
      self.monthTicketConfigIdArr = []
      //获取绑定了该凭证的月票
      API.monthTicket.FindAllBindMonthTicketConfig({
        id: self.certifiRuleModel.id
      }).then(res => {
        let monthTicketConfigIdArr = [];
        let monthTicketNameArr = [];
        let data = res.data;
        if (data) {
          data.forEach(function (obj) {
            monthTicketConfigIdArr.push(obj.configId);
            monthTicketNameArr.push(obj.name);
            self.monthTicketConfigIdArr.push(obj.configId)
          });
          self.selectedMonthTicket = monthTicketNameArr
          self.selectedMonthTicketStr = monthTicketNameArr.join(" / ")
          self.certifiRuleModel.monthTicketNames = monthTicketNameArr.join(",");
          self.certifiRuleModel.monthTicketConfigIds = monthTicketConfigIdArr.join(",");
        }
        if(!certifiRuleEdit){
          self.isShowMonthTicketVisiable = true
        }else{
          self.toOpenModal(modalName);
        }
      }, err => {
        self.showToast('获取已绑定的月票异常', 2);
      });
    },
    delCertifiRule(row) {
      var self = this;
      var params = {
        id: row.id,
        parkId: row.parkId
      };
      self.showDialog("确认删除" + row.parkName + "的月票配置?", '', function () {
        API.monthTicket.DelCertifiRule(params).then(res => {
          if (res.message) {
            self.showToast(res.message, 2, 2000);
          } else {
            self.showToast('删除成功', 1);
            self.getList();
          }
        }, err => {});
      });
    },
    submitForm(formName, modalName) {
      var self = this;
      self.$refs[formName].validate((valid) => {
        if (valid) {
          var params = {};
          params.id = self.certifiRuleModel.id;
          params.certifiName = self.certifiRuleModel.certifiName;
          params.parkId = self.certifiRuleModel.parkId;
          params.certifiStatus = self.certifiRuleModel.certifiStatus;
          params.certifiType = self.certifiRuleModel.certifiType;
          params.certifiDesc = self.certifiRuleModel.certifiDesc;
          params.agreementId = self.certifiRuleModel.agreementId;
          params.monthTicketConfigIds = self.certifiRuleModel.monthTicketConfigIds;
          if (self.certifiRuleModel.certifiSample) {
            params.certifiSample = self.certifiRuleModel.certifiSample;
            params.certifiSampleName = self.certifiRuleModel.certifiSampleName;
          }
          API.monthTicket.SaveCertifiRule(params)
            .then(res => {
              if (res.status == 1) {
                self.showToast('操作成功', 1, 2000);
                self.resetForm(formName);
                self.closed(modalName);
                self.getList();
              }
            }, err => {
              self.showToast(err.message, 2, 2000);
            })
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    resetAgreement(agreementEdit) {
      let self = this;
      self.agreenment.id = null;
      self.agreenment.title = null;
      self.agreenment.content = null;
      self.agreenment.parkName = null;
      self.agreenment.parkId = null
      self.agreementEdit = agreementEdit;
      self.list = []
    },
    // 查看协议
    showAgreementContentModal(modalName, row) {
      let self = this;
      self.resetAgreement(false);
      if (row.agreementId) {
        let params = {
          id: row.agreementId
        };
        API.monthTicket.GetAgreement(params)
          .then(res => {
            var data = res.data;
            if (data) {
              self.agreenment.title = data.agreementTitle;
              self.agreenment.content = data.agreementContent;
              self.agreenment.parkName = data.parkName;
            }
          }, err => {
            self.showToast(err.message, 2, 2000);
          })
        }
        self.toOpenModal(modalName);
    },
    async showAgreementEditModal(modalName) {
      let self = this;
      self.resetAgreement(true);
      await self.fetchParkingLotList()
      self.toOpenModal(modalName);
    },
    changeParkSelect(val) {
      let self = this;
      if (val) {
        self.agreenment.title = null;
        self.agreenment.content = null;
        var params = {
          parkId: val
        };
        API.monthTicket.GetAgreement(params)
          .then(res => {
            var data = res.data;
            if (data) {
              self.agreenment.title = data.agreementTitle;
              self.agreenment.content = data.agreementContent;
              self.agreenment.id = data.id;
              self.agreenment.parkId = data.parkId;
            } else {
              self.agreenment.parkId = val;
              self.agreenment.id = null;
            }
          }, err => {
            self.showToast(err.message, 2, 2000);
          })
      }
    },
    saveAgreement(modalName, formName) {
      let self = this;
      self.$refs[formName].validate((valid) => {
        if (valid) {
          var params = {
            agreementTitle: self.agreenment.title,
            agreementContent: self.agreenment.content,
            id: self.agreenment.id,
            parkId: self.agreenment.parkId
          };
          API.monthTicket.SaveAgreement(params)
            .then(res => {
              var data = res.data;
              if (data) {
                self.agreenment.title = data.agreementTitle;
                self.agreenment.content = data.agreementContent;
                self.agreenment.id = data.id;
                self.agreenment.parkId = data.parkId;
                self.initParkTree();
                self.closed(modalName)
                self.showToast("保存成功", 1, 2000);
              }
            }, err => {
              self.showToast(err.message, 2, 2000);
            })
        }
      });

    },
    // 获取停车场列表数据
    initParkTree() {
      let _self = this;
      return API.fetchGet('/parkingBaseData/getParkingBaseDataWithAgreementTree.do', {})
        .then(res => {
          if (res.data) {
            _self.parkingLotList = []
            let nodes = res.data;
            if(nodes.childrenNum && nodes.children){
              _self.parkingLotList = getTreeChildNodes(nodes.children,'')
              // _self.certifiRuleModel.parkId = _self.parkingLotList[0].value
            }
          } else {
            _self.parkingLotList = []
          }
        }, err => {})
    },
    selectParkSure(itemId) {
      var self = this
      let pItem = self.parkingLotList.find(elem=>{
        return elem.value==itemId
      })
      self.certifiRuleModel.agreementId = pItem.agreementId;
    },
    async openSelectMonthTicketModal(modalName) {
      let self = this;
      self.keyWord = ''
      await self.initMonthTicketTree();
      self.toOpenModal(modalName);
    },
    initMonthTicketTree() {
      let _self = this;
      _self.monthTicketList = []
      return API.fetchGet('/month_ticket/certifi_rule/getMonthTicketTree.do', {
          certifiType: _self.certifiRuleModel.certifiType,
          id: _self.certifiRuleModel.id
        })
        .then(res => {
          if (res.data != null) {
            let nodes = res.data;
            nodes.forEach(function (node) {
              node.parkNameStr = node.parkNameList.join('/')
              node.isHidden = false
            });
            _self.monthTicketList = deepCopyObjArray(nodes);
          } else {
            _self.showToast('暂时没有月票可选', 0, 3000);
          }
        }, err => {})

    },
    selectMonthTicketSure() {
      let self = this,
        monthTicketNameArr = [];
      if(Array.isArray(self.monthTicketList) && self.monthTicketList.length && self.monthTicketConfigIdArr.length){
        self.monthTicketList.forEach(elem=>{
          if(self.monthTicketConfigIdArr.indexOf(elem.configId)>-1){
            monthTicketNameArr.push(elem.name)
          }
        })
        self.selectedMonthTicket = monthTicketNameArr
        self.selectedMonthTicketStr = monthTicketNameArr.join(' / ')
        self.certifiRuleModel.monthTicketNames = monthTicketNameArr.join(",");
        self.certifiRuleModel.monthTicketConfigIds = self.monthTicketConfigIdArr.join(",");
      }else{
        self.selectedMonthTicket = ''
        self.selectedMonthTicketStr = ''
        self.certifiRuleModel.monthTicketNames = ''
        self.certifiRuleModel.monthTicketConfigIds = ''
      }
      self.closed('selectMonthTicketModal');
    },
    handleSearchChange(item) {
      switch (item.name) {
        case 'reportDimension':
          this.changeReportDimension(item);
          break;
      }
    },
    changeReportDimension(item) {
      let value = item.value,
        ThisSearchItem = this.searchList[0];
      var today = [new Date(moment().add(-7, 'days').format('YYYY-MM-DD 00:00:00')), new Date(moment().add(1, 'days').format('YYYY-MM-DD 00:00:00'))];
      var month = [new Date(moment().add(-1, 'months').format('YYYY-MM-DD 00:00:00')), new Date(moment().format('YYYY-MM-DD 00:00:00'))];
      var year = [new Date(moment().add(-1, 'years').format('YYYY-MM-DD 00:00:00')), new Date(moment().format('YYYY-MM-DD 00:00:00'))];
      switch (value) {
        case 'day':
          ThisSearchItem.type = 'datePicker';
          ThisSearchItem.pickerType = '';
          ThisSearchItem.format = 'yyyy-MM-dd';
          ThisSearchItem.value = today;
          break;
        case 'month':
          ThisSearchItem.type = 'datePicker';
          ThisSearchItem.pickerType = 'daterange';
          ThisSearchItem.format = 'yyyy-MM';
          ThisSearchItem.value = month;
          break;
        case 'year':
          ThisSearchItem.type = 'datePicker';
          ThisSearchItem.pickerType = 'daterange';
          ThisSearchItem.format = 'yyyy';
          ThisSearchItem.value = year;
          break;
        case 'custom':
          ThisSearchItem.type = 'datePicker';
          ThisSearchItem.pickerType = 'daterange';
          ThisSearchItem.format = 'yyyy-MM-dd';
          ThisSearchItem.value = today;
          break;
      }
    }
  }
}